<?php

defined('MYLITS') ? '' : exit('No direct script access allowed');

/**
 * @version     1.0.0
 * @package     mylits engine
 * @license     GNU General Public License version 3
 * @author      Arfan Fudyartanto D N <arfan@mylits.com> - http://engine.mylits.com
 */
class Mylits_System {

    private static $instance;

    private function __construct() {
        
    }

    /**
     * This method will return Mylits_System object
     * 
     * @return object Mylits_System
     */
    public static function getInstance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Method to render component
     * 
     * @param string $html -> html text which contain rendering syntax, <mylits:renderer:{component_name}/>
     * @return type content of the component
     */
    public static function getRenderedObject($html) {
        if (preg_match_all('/<mylits:renderer:(.*?)\/>/', $html, $match)) {
            $components = $match[1];

            foreach ($components as $comp) {

                $comp_name = $comp;
                $arr = explode(':', $comp);
                if (count($arr) >= 1) {
                    $comp_name = $arr[0];
                }

                $ctrl = explode('.', $comp_name);
                $path = APP_DIR . '/components/comp.' . $comp_name . '/' . end($ctrl) . '.ctrl.php';
                if (is_file($path)) {
                    require_once $path;
                    $class = end($ctrl) . 'Controller';
                    $objComp = new $class;
                    $objComp->component = $comp_name;
                    $objComp->component_path = APP_DIR . '/components/comp.' . $comp_name . '/';
                    if ($objComp->is_public) {
                        $content = $objComp->view();
                    } else {
                        $model = Mylits_Loader::getModel('main', ENGINE_DIR . '/core/models/main.mdls.php');
                        $user = Mylits_User::getInstance();
                        if ($user::$guest) {
                            $content = "Permission denied";
                        } else if ($model->checkComponentPermission($comp_name)) {
                            $content = $objComp->view();
                        } else {
                            $content = "Permission denied";
                        }
                    }

                    $html = str_replace('<mylits:renderer:' . $comp . '/>', $content, $html);
                }
            }
        }
        return $html;
    }

    /**
     * Method to checq any request ($_GET & $_POST) is already set
     * 
     * @param string $name -> request key
     * @return boolean, true if exist and false if not exist
     */
    public static function issetRequest($name) {
        $data = self::filteringInput();
        if (isset($data[$name])) {
            $result = true;
        } else {
            $result = false;
        }
        return $result;
    }

    /**
     * Method to get request value ($_POST and $_GET)
     * 
     * @param string $name ->key of request
     * @return value
     */
    public static function getRequest($name) {
        $data = self::filteringInput();
        $result = '';
        if (isset($data[$name])) {
            $result = $data[$name];
        }
        return $result;
    }

    /**
     * Method to redirect page
     * 
     * @param string $component
     * @param string $task
     */
    public static function redirect($component) {
        header('Location: ' . BASE_URL . $component);
        exit;
    }

    /**
     * Method to filter input
     * 
     * @return array request
     */
    private static function filteringInput() {
        $uri = $_SERVER['REQUEST_URI'];
        $argsGet = substr($uri, (strpos($uri, '?') + 1));
        $request = array();
        $itemArgs = explode('&', $argsGet);
        foreach ($itemArgs as $item) {
            $index = substr($item, 0, strpos($item, '='));
            if(empty($index)){
                $index = $item;
            }
            $value = substr($item, (strpos($item, '=') + 1));
            if (!empty($index)) {
                $request[$index] = $value;
            }
        }
        foreach ($_POST as $key => $post) {
            $request[$key] = $post;
        }
        return $request;
    }

    /**
     * Method to assign system message
     * 
     * @param string $class -> css class
     * @param string $msg -> content
     */
    public static function addSystemMsg($class, $msg) {
        $_SESSION['SYS_MSG'][] = array(
            'class' => $class,
            'message' => $msg
        );
    }

    /**
     * This methid to check request coming from ajax request
     * 
     * @return boolean
     */
    public static function isAjaxRequest() {
        return @ $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
    }

    /**
     * This method to get current url
     * 
     * @return string current url (full path)
     */
    public static function getCurrentUrl() {
        $pageURL = 'http';
        if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return substr($pageURL, 0, strpos($pageURL, '?'));
    }

}

?>
